<?php
/**
* alltosun.com 消息中心控制器 index.php
* ============================================================================
* 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* $Author: 高昂 (gaoa@alltosun.com) $
* $Date: 2014-8-8 下午3:56:59 $
* $Id$
*/

require_once MODULE_PATH.'/message_center/helper/vendor/autoload.php';

use JPush\Model as M;
use JPush\JPushClient;
use JPush\JPushLog;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

use JPush\Exception\APIConnectionException;
use JPush\Exception\APIRequestException;




class Action
{
    private $per_page = 20;
    private $message_json = '';

    /**
     * 去掉消息用户关系表中的非法信息
     */
    public function filter_message_user_data()
    {
        // 获取消息关系表中所有的数据
        $message_user_list = _model('message_user')->getList(array('`id` >='=>0));
        echo _model('message_user')->getTotal(array('`id` >='=>0)),'<br/>';
        
        
        // 获取消息中心的所有消息id
        $all_msg_id = _model('message_center')->getFields('id', array('`id` >='=>0));
        
        foreach ($message_user_list as $k=>$v) {
            
            if (!in_array($v['msg_id'], $all_msg_id)) {
                var_dump(in_array($v['msg_id'], $all_msg_id));die;
            	_model('message_user')->delete(array('id'=>$v['id']));
            	continue;
            }
            
            $user_id = $v['user_id'];
            $role_id = user_helper::get_user_role_id($user_id);
            $msg_id  = $v['msg_id'];
            $msg_info = _uri('message_center', $msg_id);
            switch ($role_id) {
            	case user_config::AGENCY:
            	    if ($msg_info['push_range'] != 8) {
            	       if (!in_array($msg_info['push_range'], array(0, 1, 3, 5, 7))) {
            	    	  _model('message_user')->delete(array('msg_id'=>$msg_id, 'user_id'=>$user_id));
            	       }
            	    }
            	    break;
            	case user_config::MARKETING:
            	    if ($msg_info['push_range'] != 8) {
            	    	if (!in_array($msg_info['push_range'], array(0, 2, 3, 6, 7))) {
            	    		_model('message_user')->delete(array('msg_id'=>$msg_id, 'user_id'=>$user_id));
            	    	}
            	    }
            	    break;
            	case user_config::STORE_MANAGER:
            	case user_config::STORE_OWNER:
            	    if ($msg_info['push_range'] != 8) {
            	    	if (!in_array($msg_info['push_range'], array(0, 4, 5, 6, 7))) {
            	    		_model('message_user')->delete(array('msg_id'=>$msg_id, 'user_id'=>$user_id));
            	    	}
            	    }
            	    break;
            }
        }
        
        echo _model('message_user')->getTotal(array('`id` >='=>0));
        
    }

    /**
    * 消息列表
    */
    public function index()
    {
        $page          = Request::Get('page_no', 1);
        $status        = Request::Get('status', 1);
        $is_advenced   = Request::Get('is_advenced', 0);
        $search_filter = Request::Get('search_filter', array());

        $filter = array();
        $filter['status'] = $status;

        if (isset($search_filter['title']) && $search_filter['title']) {
            $filter[' `title` LIKE '] = '%'.$search_filter['title'].'%';
        }

        if (isset($search_filter['res_name']) && $search_filter['res_name']) {
            $filter['res_name'] = $search_filter['res_name'];
        }

        if (isset($search_filter['start_date']) && $search_filter['start_date']) {
            $filter['add_time >='] = $search_filter['start_date'].' 00:00:00';
        }
        if(isset($search_filter['end_date']) && $search_filter['end_date']) {
            $filter['add_time <='] = $search_filter['end_date'].' 23:59:59';
        }

        $message_list = array();

        
        $message_list = get_data_list('message_center', $filter, ' ORDER BY `add_time` DESC ', $page, $per_page = 20);
        
        foreach ($message_list as $k => $v) {
            if (8 == $v['push_range']) {
            	// 如果是个人的则获取消息用户关系表对应的用户id,进而获取用户名
            	$message_user_info = array();
            	$message_user_info = _uri('message_user', array('msg_id'=>$v['id']));
            	$user_info = array();
            	$user_info = _uri('user', array('id'=>$message_user_info['user_id']));
            	$message_list[$k]['user_name'] = $user_info['user_name'];
            }
        }
        
        Response::assign('res_name_list', message_center_config::$res_name_list);
        Response::assign('message_list', $message_list);
        Response::assign('status', $status);
        Response::assign('search_filter', $search_filter);
        Response::assign('is_advenced', $is_advenced);

        Response::display('admin/message_list.html');
    }

    /**
    * 增加消息表单
    */
    public function add()
    {
        Response::assign('res_name_list', message_center_config::$res_name_list);
        // @TODO 获取角色列表
        Response::assign('role_list', array());

        Response::display('admin/add.html');
    }

    /**
    * 发送消息
    */
    public function create()
    {

        $message      = Request::getParam('message', array());
        $push_range   = Request::getParam('push_range');
        $message['add_time'] = date('Y-m-d H:i:s', time());
        $message['push_range'] = $push_range;        
        $message['title']  = message_center_helper::get_push_template($message['res_name'], array('title'=>$message['title']))['title'];
        $user_id = Request::getParam('user_id', 0);

        $result = array();

        $id = _model('message_center')->create($message);
        
        $url = '';
        
        if (!$id) {
        	return '消息保存失败!';
        } else {
            if (trim($message['url'], ' ') == '') {
            	$url = AnUrl('message_center/notice_detail?id='.$id);
            	_model('message_center')->update($id, array('url'=>$url));
            }
        }        

        //处理消息内容
        $msg = array();
        $msg['content']  = $message['title'];
        $msg['res_id']   = $id;
        $msg['res_name'] = $message['res_name'];
        if ($msg['res_name'] == 'notice' || $msg['res_name'] == 'event') {
        	$msg['url'] = $url;
        }
        // easy push
        switch ($push_range) {
            // 所有人
            case 0:
                $msg['role_id'] = 0;
                // 推送市场人员和经销商
                _widget('push')->send($msg, '', 'manage');
                // 推送商家段
                _widget('push')->send($msg, '', 'store');
                break;
            //经销商 5 每分钟600次推送
            case 1:
                $msg['role_id'] = 5;
                $dealer_ids = user_helper::get_role_user_ids(5);
                
                //0.1秒 = 100000微秒
                $num = count($dealer_ids);
                $cycle_num = ceil($num/1000);
                if ($num <= 1000) {
                	_widget('push')->send($msg, $dealer_ids, 'manage');
                } else {
                    for ($i = 0; $i < $cycle_num; $i+=1000) {
                        $tmp_dealer_ids = array_slice($dealer_ids, $i, 1000);
                        _widget('push')->send($msg, $tmp_dealer_ids, 'manage');
                        usleep(100000);
                    }
                    
                }
                
                //var_dump($dealer_ids);die;
                break;
            //市场人员 10
            case 2:
                $msg['role_id'] = 10;
                $marketing_ids = user_helper::get_role_user_ids(10);
                //0.1秒 = 100000微秒
                $num = count($marketing_ids);
                $cycle_num = ceil($num/1000);
                for ($i = 0; $i < $cycle_num; $i+=1000) {
                    $tmp_marketing_ids = array_slice($marketing_ids, $i, 1000);
                    _widget('push')->send($msg, $tmp_marketing_ids, 'manage');
                    usleep(100000);
                }
                break;
            // 经销商和市场人员
            case 3:
                $msg['role_id'] = 0;
                _widget('push')->send($msg, '', 'manage');
                break;
            // 商户端 15和20
            case 4:
                $msg['role_id'] = 0;
                _widget('push')->send($msg, '', 'store');
                break;
                
            case 8:
                
                //获取用户的角色
                $user_role_id = user_helper::get_user_role_id($user_id);
                $msg['role_id'] = $user_role_id;
                if ($user_role_id == 5 || $user_role_id == 10) {
                    _widget('push')->send($msg, array($user_id), 'manage');
                } else {
                    _widget('push')->send($msg, array($user_id), 'store');
                }
                break;

        }

        Response::redirect('message_center/admin');

        
    }

    /**
    * 编辑消息
    */
    public function edit()
    {
        $id = Request::getParam('id', 1);

        $message = _uri('message_center', $id);

        Response::assign('is_edit', 1);
        Response::assign('res_name_list', message_center_config::$res_name_list);
        Response::assign('message', $message);
        Response::display('admin/add.html');
    }
    
    /**
     * 消息更新只在公告类下
     */
    public function update()
    {
        $id = Request::getParam('id', 0);
        $message = Request::getParam('message', array());
        if (!$id) {
        	return '没有选择公告!';
        }
//         an_dump($message);
        if ($message['url'] == '') {
        	//自动生成url
        	$url = AnUrl('message_center/notice_detail?id='.$id);
        	$message['url'] = $url;
        }
        _model('message_center')->update($id, $message);
        
        Response::assign('status', 1);
        Response::redirect(AnUrl('message_center/admin?status=1'));
    }
    

    /**
    * 伪删除
    */
    public function delete()
    {
        $id = Request::getParam('id');

        $ids = explode(',', $id);
        foreach ($ids as $k => $id) {
            _model('message_center')->update($id, array('status' => 0));    
        }

        return 'ok';
    }

    /**
    * 恢复
    */
    public function change_status()
    {
        $id = Request::getParam('id');
        _model('message_center')->update($id, array('status' => 1));

        Response::assign('status', 1);
        Response::redirect(AnUrl('message_center/admin?status=1'));
    }

    /**
    * 物理删除
    */
    public function delete_message()
    {
        $id = Request::getParam('id');

        _model('message_center')->delete($id);

        return 'ok';
    }

}

?>
